const { host } = require('../../mockConfig')

Page({
  data: {
    latitude: 0,
    longitude: 0,
    markers: []
  },

  onShow() {
    this._loadData()
  },

  onReady() {
    // 获取地图对象
    this.mapctx = wx.createMapContext("map")
    
    // 获取用户位置
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        const latitude = res.latitude
        const longitude = res.longitude
        
        this.setData({
          latitude,
          longitude
        })
      }
    })
  },

  _loadData() {
    // 拉取地图数据
    wx.request({
      url: `${host}/data`,
      success: res => {
        const markers = res.data.map( ({ id, latitude, longitude, type }) => {
          return {
            id,
            latitude,
            longitude,
            iconPath: `/resources/${type}.png`,
            width: '40rpx',
            height: '40rpx'
          }
        })

        this.setData({
          markers
        })
      }
    })
  },

  handleCenterTap() {
    this.mapctx.moveToLocation()
  },

  handlePublish() {
    wx.navigateTo({
      url: '/pages/publish/publish',
    })
  },

  handleMarkerTap({markerId}) {
    wx.navigateTo({
      url: '/pages/details/details?id=' + markerId,
    })
  }
})